package com.bfb;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.bfb.helpers.User;
import com.facebook.android.Facebook;

public class Main extends Activity {

	SharedPreferences mPref;
	static User user;
	static Context mContext;
	static final Facebook facebook = new Facebook("343570578990435");

	static String android_id = null;
	public static final String SERVER = "bfbmobileserver.appspot.com";

	// public static final String SERVER = "10.0.2.2:8080";
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		facebook.authorizeCallback(requestCode, resultCode, data);
	}
	
	public void setUser(SharedPreferences sp, String androidId)
	{
		user = new User(androidId,sp);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.edit_profile_only, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		if (item.getItemId() == R.id.edit_profile_menuItem) {
			// UserProfileActivity.getInfoFromFB(this);

			Intent BIntent = new Intent(this, UserProfileActivity.class);

			startActivity(BIntent);

		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * {@link OnClickListener} for the "New Dish" button. Goes to the
	 * {@link CreateDishActivity}.
	 * 
	 * @param v
	 * 
	 * @author Rawan Khalil (rawan.tkhalil@gmail.com)
	 */
	public void addNewDish(View v) {
		startActivity(new Intent(getBaseContext(), CreateDishActivity.class));
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		/*
		 * This is used to detect if the user is running the app for the first
		 * time
		 */
		Log.e("IN create", "ON");
		mContext = this.getApplicationContext();
		android_id = Secure.getString(mContext.getContentResolver(),
				Secure.ANDROID_ID);
		mPref = mContext.getSharedPreferences("myAppPrefs", 0);
		boolean firstTime = mPref.getBoolean("firstRun", true);
		SharedPreferences.Editor edit = mPref.edit();
		Log.e("first RUn", firstTime + "");
		//user = new User(android_id, mPref);
		setUser(mPref, android_id);
		if (firstTime)
			identifyUser();

		/*
		 * ServerUtilities.background(new Runnable() { public void run() { try {
		 * DefaultHttpClient CLIENT = new DefaultHttpClient(); HttpResponse resp
		 * = CLIENT.execute(new HttpGet(SERVER + PATH)); final String respStr =
		 * EntityUtils.toString(resp .getEntity()); if
		 * (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
		 * runOnUiThread(new Runnable() { public void run() {
		 * Toast.makeText(getBaseContext(), respStr, Toast.LENGTH_LONG).show();
		 * // TextView t = (TextView) // findViewById(R.id.textId); //
		 * t.setText(respStr); } }); } else throw new Exception(respStr); }
		 * catch (Exception e) { Log.e(TAG, e.getMessage(), e);
		 * runOnUiThread(new Runnable() { public void run() {
		 * Toast.makeText(getBaseContext(), "ERROR", Toast.LENGTH_LONG).show();
		 * // TextView t = (TextView) // findViewById(R.id.textId); //
		 * t.setText("ERROR"); } }); } } });
		 */
	}

	/*
	 * This method will set the sharedPreference which indicates if first run to
	 * false to not Identify the user on every run of the app It also
	 * responsible of send the user device ID to the server
	 */

	private void identifyUser() {
		Log.e("in identify", "identify");

		try {
			// JSONObject json = new JSONObject();
			// json.put("key", "test2");
			// HttpParams httpParams = new BasicHttpParams();
			// HttpConnectionParams.setConnectionTimeout(httpParams,3000);
			// HttpConnectionParams.setSoTimeout(httpParams, 3000);
			HttpClient client = new DefaultHttpClient();
			String url = "http://" + SERVER + "/add/user";
			HttpPost request = new HttpPost(url);
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("key", android_id));
			request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			// request.setEntity(new
			// ByteArrayEntity(json.toString().getBytes("UTF8")));
			// request.setHeader("json", json.toString());
			// Log.e("response",request.toString());
			HttpResponse response = client.execute(request);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			Log.e("statusCode", statusCode + "");
			StringBuilder respStr = new StringBuilder();
			if (statusCode == 200) {

				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					respStr.append(line);
				}
			}
			Log.e("Response", respStr.toString());
		} catch (Throwable t) {
			Log.e("fail", t.getMessage());
			Toast.makeText(this, "Request failed: " + t.toString(),
					Toast.LENGTH_LONG).show();
		}
		Log.e("android ID", android_id + "");
		SharedPreferences.Editor edit = mPref.edit();
		edit.putBoolean("firstRun", false);
		edit.commit();

	}

	/**
	 * {@link OnClickListener} for the "Play" button. Goes to the
	 * {@link DishTypeActivity}.
	 * 
	 * @param v
	 * 
	 * @author Rawan Khalil (rawan.tkhalil@gmail.com)
	 */
	public void playOnClick(View v) {
		Intent dishTypesIntent = new Intent(this, DishTypeActivity.class);
		startActivity(dishTypesIntent);
	}

	public void Browse(View v) {
		Intent BIntent = new Intent(this, Browse.class);
		startActivity(BIntent);

	}

	// public void BrowseR(View v1) {
	// Intent BIntent = new Intent(this, ListDishes.class);
	// BIntent.putExtra("browse", "Rest");
	// startActivity(BIntent);
	//
	// }
	//
	// public void BrowseN(View v2) {
	// Intent BIntent = new Intent(this, ListDishes.class);
	// BIntent.putExtra("browse", "Near");
	// startActivity(BIntent);
	//
	// }

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
			Toast.makeText(getBaseContext(), "Goodbye!", Toast.LENGTH_SHORT)
					.show();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}
	//
	// @Override
	// public void onBackPressed() {
	//
	// super.onBackPressed();
	// }
}
